package com.yesallchina.wxapp.officialaccount.api;

import com.yesallchina.wxapp.officialaccount.api.beans.ParamName;
import com.yesallchina.wxapp.officialaccount.service.WxOfficialAccountInitializer;
import com.yesallchina.wxapp.officialaccount.utils.WxHttpUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;

/**
 * 用户管理
 */
public class UserManageApi {

    private final static Logger log = LoggerFactory.getLogger(UserManageApi.class);

    private WxOfficialAccountInitializer wxInit;

    private BasicSupportApi basicSupport;

    public UserManageApi(BasicSupportApi basicSupport){
        this.wxInit = basicSupport.getWxInit();
        this.basicSupport = basicSupport;
    }


    /**
     * 通过openid，获取用户信息
     *
     * @param openid
     * @return
     */
    public String getUser(String openid){
        return getUser(openid,0);
    }

    private String getUser(String openid, int retry){
        if (retry > 2) {
            return null;
        }
        try {
            String url = wxInit.getApiProp().getUserByOpenid();
            Map<String, String> params = new HashMap<>();
            params.put(ParamName.ACCESS_TOKEN, basicSupport.getAccessToken());
            params.put(ParamName.OPEN_ID, openid);
            params.put(ParamName.LANG, "zh_CN");
            String response = WxHttpUtils.doGet(url, params, wxInit.getCommonProp());
            if (log.isDebugEnabled()) {
                log.debug("[openid获取用户基本信息] : {}", response);
            }
            if (basicSupport.isError(response)) {
                if (basicSupport.isInvalidAccessToken(response)) {
                    Thread.sleep(1000);
                    return getUser(openid, ++retry);
                }
            }
            return response;
        } catch (Exception e) {
            log.error("[获取用户基本信息] : 发生错误 \r\n  {}", e);
            return getUser(openid, ++retry);
        }
    }
}
